#region File Header
//----------------------------------------------------------------
// Copyright (C) 2002 Stefan Kyntchev
// All rights reserved.
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY 
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT 
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR 
// FITNESS FOR A PARTICULAR PURPOSE.
//----------------------------------------------------------------
#endregion File Header

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Security;
using System.Web.Mail;
using AirWeb.Security.FileSecurity;
using AirWeb.Support.Diagnostics;
using Role=AirWeb.Security.Role;
using SecurityMgr=AirWeb.Security.SecurityMgr;
using User=AirWeb.Security.User;

namespace FlashBack.Web
{
	/// <summary>
	/// Summary description for ManageUsers.
	/// </summary>
	public partial class ManageUsers : PageBase
	{

		ArrayList m_RoleList = new ArrayList();
		int m_num_admins = 0;

		public ManageUsers()
		{
			Page.Init += new System.EventHandler(Page_Init);
		}

		protected void Page_Load(object sender, System.EventArgs e)
		{
			Response.Expires = -1;
			ValidateCurrentUserIsAdministrator();

			// Build the role array;
			foreach(Role r in SecurityMgr.Instance.Roles)
			{
				m_RoleList.Add(r.Name);
			}

			BuildUserTable();

			if(!IsPostBack)
			{
				// build a role list used to create a new user
				newUserRole.DataSource = m_RoleList;
				newUserRole.DataBind();
			}

			ErrorText.Visible = false;
		}

		/// <summary>
		/// Creates a data table with user content and binds it to the data grid control
		/// </summary>
		protected void BuildUserTable()
		{
			DataTable dt = new DataTable();
			DataRow dr;
			dt.Columns.Add(new DataColumn("Name", typeof(string)));
			dt.Columns.Add(new DataColumn("Email", typeof(string)));
			dt.Columns.Add(new DataColumn("Can Upload", typeof(string)));
			dt.Columns.Add(new DataColumn("Role", typeof(string)));
			m_num_admins = 0;

			foreach (User a in SecurityMgr.Instance.Users)
			{
				dr = dt.NewRow();
				dr[0] = a.Name;
				dr[1] = a.Email;

				ExtraUserData eud = null;
				try
				{
					eud = (ExtraUserData)a.ExtraData;
				}
				catch
				{}

				if( eud != null && eud.CanUpload == true ) 
					dr[2] = "Yes";
				else
					dr[2] = "No";
 
				dr[3] = a.UserRole.Name;

				dt.Rows.Add(dr);

				if(a.IsAdministrator())
					m_num_admins++;
			}
            
			UsersGrid.DataSource = new DataView(dt);
			UsersGrid.DataBind();
		}

		/// <summary>
		/// Invoked when user clicks on the links in Actions column
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		public void ItemCommand(object sender, DataGridCommandEventArgs e)
		{
			if(e.CommandName == "DeleteUser")
			{
				DeleteUser(e.Item.Cells[0].Text);
			}
		}

		/// <summary>
		/// Deletes the specified user from the system
		/// </summary>
		/// <param name="i_user">Username to delete</param>
		protected void DeleteUser(string i_user)
		{
			try
			{
				SecurityMgr.Instance.RemoveUser(i_user);
				SecurityMgr.Instance.Serialize();
				ApplicationLog.WriteTrace("User deleted: " + i_user);
			}
			catch(ArgumentException ex)
			{
				DisplayError(ex);
				ApplicationLog.WriteError("Error occured while deleting a user " + i_user + " -> "  + ex.Message);
			}

			BuildUserTable();
		}

		/// <summary>
		/// Displays an error message on the page
		/// </summary>
		/// <param name="ex"></param>
		protected void DisplayError(Exception ex)
		{
			ErrorText.Text = "Error executing request. " + ex.Message;				
			ErrorText.Visible = true;
		}

		/// <summary>
		/// Invoked when add user button is clicked
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		protected void AddUser(object sender, CommandEventArgs e)
		{
			if(newUserPassword.Value != repeatPassword.Value)
			{
				ErrorText.Text = "Password and Repeat Pasword fields don't match. Please enter the same password in both fields.";
				ErrorText.Visible = true;
				return;
			}

			try
			{
				SecurityMgr.Instance.AddUser(newUserName.Text,newUserPassword.Value,newUseremail.Text,newUserRole.SelectedItem.Text,new ExtraUserData(newCanUpload.Checked));
				SecurityMgr.Instance.Serialize();
				ApplicationLog.WriteTrace("User added: " + newUserName.Text);
			}
			catch(ArgumentException ex)
			{
				DisplayError(ex);
				ApplicationLog.WriteError("Error occured while adding a user: " + newUserName.Text + " -> "  + ex.Message);
			}

			BuildUserTable();
		}

		protected void onRowBound(object sender, DataGridItemEventArgs e)
		{
			if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
			{
				TableCell c = (TableCell)e.Item.Cells[3];

				string username = e.Item.Cells[0].Text;

				// Don't allow deleting of the last administrator or the current user
				User u = SecurityMgr.Instance.GetUserByName(username);
				if(u == null)
				{
					e.Item.Cells[0].Text = e.Item.Cells[0].Text + " (user has been deleted)";
					ApplicationLog.WriteError("Unable to find user by name. User: " + username);
				}

				if(m_num_admins == 1 && u.IsAdministrator() || CurrentUser.Equals(u))
				{
					Control c0 = e.Item.Cells[3].FindControl("delete");
					if(c0 != null)
						c0.Visible = false;
				}
				else
				{
					DropDownList d = new DropDownList();
					d.CssClass = "searchInput";
					d.DataSource = m_RoleList;
					d.Attributes["User"] = username;
					d.AutoPostBack = true;
					d.SelectedIndexChanged += new System.EventHandler(this.OnUserRoleChanged);
					d.DataBind();
					d.SelectedIndex = m_RoleList.IndexOf(c.Text);
					c.Controls.Clear();
					c.Controls.Add(d);
				}

				if(e.Item.Cells[1].Text == "&nbsp;")
				{
					Control c1 = e.Item.Cells[3].FindControl("sendEmail");
					if(c1 != null)
						c1.Visible = false;
				}
			}
		}

		/// <summary>
		/// Invoked when the the existing role of the user is changed
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		public void OnUserRoleChanged(object sender, EventArgs e)
		{	
			try
			{
				DropDownList d = (DropDownList)sender;
				string user = d.Attributes["User"];
				string newrole = d.SelectedItem.Text;
				SecurityMgr.Instance.SetUserRole(user,newrole);
				SecurityMgr.Instance.Serialize();
				ApplicationLog.WriteTrace("User role changed. User:" + user + " -> " + newrole);				
			}
			catch(ArgumentException ex)
			{
				DisplayError(ex);
				ApplicationLog.WriteError("Error occured while changing user role: " + ex.Message);
			}

			BuildUserTable();
		}

		protected void Page_Init(object sender, EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
		}

		#region Web Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{    

		}
		#endregion
	}
}
